package com.ourmovieguy;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class NYTMovieManager {

	private static String search_base = "http://api.nytimes.com/svc/movies/v2/reviews/search.xml?&response-format=XML&api-key=70b71382c2a57dd101080000f0b1f3e9:4:59939697&query=";
	
	public static List<NYTMovie> getMoviesFromProvider(String query)
	{
		List<NYTMovie> ret = null;
			
		try {
			if (query == null || query.isEmpty())
				throw new IllegalArgumentException("query is empty");

			String term = query.replace(" ", "+");
			String searchurl = search_base + term;
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			URL url = new URL(searchurl);
			Document dom = db.parse(url.openStream());
			ret = movieFromXmlDocument(dom);		
		}
		catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		return ret;
	}

	private static NYTMovie movieFactory(Element reviewElement) {
		String url = "";
		NodeList nl = reviewElement.getElementsByTagName("url");
		
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			if (null != el.getFirstChild()) {
				url =  el.getFirstChild().getNodeValue();
			}
		}
		
		NYTMovie movie = new NYTMovie(
				StringFromTag(reviewElement, "display_title"),
				StringFromTag(reviewElement, "mpaa_rating"),
				StringFromTag(reviewElement, "publication_date"),
				StringFromTag(reviewElement, "capsule_review"),
				url);
		return movie;
	} 
	
	private static List<NYTMovie> movieFromXmlDocument(Document dom) {
		List<NYTMovie> movies = new ArrayList<NYTMovie>();
		
		//get the root elememt
		Element docEle = dom.getDocumentElement();
		//get a nodelist of <employee> elements
		NodeList nl = docEle.getElementsByTagName("review");
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {
				Element el = (Element)nl.item(i);
				movies.add(movieFactory(el));
			}
		}

		return movies;
	}
	
	private static String StringFromTag(Element el, String tagname) {
		NodeList nl = el.getElementsByTagName(tagname);
		Element el1 = (Element)nl.item(0);
		if (null != el1.getFirstChild()) {
			return el1.getFirstChild().getNodeValue();
		} else {
			return "";
		}
	}

	public static String getJSON(List<NYTMovie> movies) {
		
		boolean first = true;
		StringBuilder jsonBuilder = new StringBuilder();
		jsonBuilder.append("({\"items\":[\n");
		for (NYTMovie movie : movies)
		{
			if (first)
				first = false;
			else
				jsonBuilder.append(",\n");
			
			String movieJson = movie.toJSON();
			jsonBuilder.append(movieJson);
		}
		jsonBuilder.append("]})");
		
		return jsonBuilder.toString();
	}
	
	public static String getSmallJSON(List<NYTMovie> movies) {

		boolean first = true;
		StringBuilder jsonBuilder = new StringBuilder();
		jsonBuilder.append("({\"items\":[\n");
		for (NYTMovie movie : movies)
		{
			if (first)
				first = false;
			else
				jsonBuilder.append(",\n");
			
			String movieJson = movie.toSmallJSON();
			jsonBuilder.append(movieJson);
		}
		jsonBuilder.append("]})");
		
		return jsonBuilder.toString();
	}
}
